﻿unit FormMain;

interface

uses
  qjson,
  TJDownFile,TJTencentCos,
  SysUtils, Variants, Classes,
  Vcl.Graphics,Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, bsSkinCtrls,
  bsSkinData, BusinessSkinForm, Vcl.Mask, bsSkinBoxCtrls, Vcl.ComCtrls;

type
  TForm1 = class(TForm)
    bsBusinessSkinForm1: TbsBusinessSkinForm;
    bsSkinPanel1: TbsSkinPanel;
    bsklbl1: TbsSkinLabel;
    bsSkinEdit1: TbsSkinEdit;
    bsSkinButton1: TbsSkinButton;
    bsknbtnDown: TbsSkinButton;
    ProgressBar1: TProgressBar;
    bsCompressedStoredSkin1: TbsCompressedStoredSkin;
    bsSkinData1: TbsSkinData;
    procedure FormCreate(Sender: TObject);
    procedure bsSkinButton1Click(Sender: TObject);
    procedure bsknbtnDownClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);

  private
    FWorkDir    :   string;
    FDownDir    :   string;
    FDownFile   :   TQDownFile;

    FCosHard    :   TCosHard;
    FCosObject  :   TCosObject;
    FCosWixPath :   string;

    procedure CheckDirJson(AJson:TQJson;DesDir:String);
    procedure DownLoadJson(AJson:TQJson;DesDir:String);
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Key  : Integer;
  Form1: TForm1;

implementation

{$R *.dfm}

uses
    Winapi.Windows,
    TJBSControl,
    TJCommFun,
    TJSecondCommFun;

function WixToUUId(Addr:string):string;
var
  CurPos    :   Integer;
begin
  CurPos := Pos('https://ucarecdn.com/',Addr);
  if CurPos > 0 then
  begin
    //21为https://ucarecdn.com/字符的长度
    Result :=  Addr.Substring(CurPos-1 + 21);
    Result := Result.Replace('/original','',[rfReplaceAll]);
    Result := Result.Replace('/','__',[rfReplaceAll]);
    Result := Result.Replace('?','___',[rfReplaceAll]);
  end
  else
    Result :=  Addr;
end;

procedure TForm1.CheckDirJson(AJson:TQJson;DesDir:String);
var
  ListStr   :   TStringList;
  i         :   Integer;
  OneJson   :   TQJson;
  DelList   :   TStringList;
  CurStr    :   string;
begin
  DelList :=   TStringList.Create;
  ListStr :=   TStringList.Create;
//  AnFindFullFileToDir(FWorkDir+'/DownLoad','*.*',ListStr,2);
  AnFindFullFileToDir(FDownDir,'*.*',ListStr,2);
  for i := 0 to ListStr.Count-1 do
  begin
    for OneJson in AJson do
    begin
      CurStr :=  OneJson.ItemByName('Name').AsString;
      if Pos(CurStr,ListStr.Strings[i]) >= 0 then
      begin
        DelList.Add(IntToStr(i));
        CopyFile(PChar(FDownDir+'/'+ListStr.Strings[i]),PChar(FWorkDir+DesDir+ListStr.Strings[i]),False);
        //CopyFile(PChar(FWorkDir+'/DownLoad/'+ListStr.Strings[i]),PChar(FWorkDir+DesDir+ListStr.Strings[i]),False);
        break;
      end;
    end;
  end;
//删除已经存在的索引
  for i := 0 to DelList.Count-1 do
    AJson.Delete(StrToInt(DelList.Strings[DelList.Count-1-i]));

  FreeAndNil(ListStr);
  FreeAndNil(DelList);
end;


procedure TForm1.DownLoadJson(AJson:TQJson;DesDir:String);
var
  OneJson   :   TQJson;
  LvRetI    :   Integer;
begin
  ProgressBar1.Min := 0;
  if AJson.Count = 0 then
  begin
    ProgressBar1.Visible := True;
    ProgressBar1.Max := 100;
    ProgressBar1.Position := 100;
    Exit;
  end;

  ProgressBar1.Max := AJson.Count;
  ProgressBar1.Visible := True;
  for OneJson in AJson do
  begin
    ProgressBar1.Position := OneJson.ItemIndex;
    LvRetI := FDownFile.GetFile(OneJson.ValueByName('Url',''),FDownDir+'/'+OneJson.ValueByName('Name',''));
//    LvRetI := FDownFile.GetFile(OneJson.ValueByName('Url',''),FWorkDir+'/DownLoad/'+OneJson.ValueByName('Name',''));
//如果正常返回则拷贝文件
    if LvRetI = 0 then
      CopyFile(PChar(FDownDir+'/'+OneJson.ValueByName('Name','')),PChar(FWorkDir+DesDir+OneJson.ValueByName('Name','')),False);
//      CopyFile(PChar(FWorkDir+'/DownLoad/'+OneJson.ValueByName('Name','')),PChar(FWorkDir+DesDir+OneJson.ValueByName('Name','')),False);

    OneJson.Add('State').AsInteger :=LvRetI;
    if (OneJson.ItemIndex mod 4)=0 then
      DelaySwitch(100);
    ProgressBar1.Refresh;
  end;
  ProgressBar1.Position :=  AJson.Count;
//  ProgressBar1.Refresh;
end;


procedure TForm1.bsknbtnDownClick(Sender: TObject);
var
  ListStr   :   TStringList;
  ListItem  :   TStringList;
  i         :   Integer;
  AJson     :   TQJson;
  CurStr    :   string;
  CurPos    :   Integer;
  OneJson   :   TQJson;

begin
  if not FilePathExistStr(bsSkinEdit1.Text) then
  begin
    SetShowMessageBox(2,'Please Select One File.');
    Exit;
  end;
  AJson := TQJson.Create;
  ListStr :=  TStringList.Create;
  try
    ListStr.LoadFromFile(bsSkinEdit1.Text);
    //创建目录
    AJson.Add('DesDir').AsString :=  '/'+ChangeFileExt(ExtractFileName(bsSkinEdit1.Text),'');
    if not FolderExistStr(FWorkDir+AJson.ValueByName('DesDir','')) then
      CreateDir(FWorkDir+AJson.ValueByName('DesDir',''))
    else
      DeleteDir(FWorkDir+AJson.ValueByName('DesDir',''),True);     //删除目录文件
    CurStr :=  AJson.ValueByName('DesDir','')+'_'+FormatDateTime('yyMMddhhmmss',now)+'.csv';
    CurPos := FCosObject.UpLoadFile(FCosWixPath+CurStr,bsSkinEdit1.Text);
  except on E: Exception do
    begin
      SetShowMessageBox(1,E.Message);
      FreeAndNil(ListStr);
      FreeAndNil(AJson);
      Exit;
    end;
  end;
  if CurPos <> 0 then
  begin
    SetShowMessageBox(2,'please check network.');
    FreeAndNil(ListStr);
    FreeAndNil(AJson);
    Exit;
  end;

  bsknbtnDown.Enabled := False;
  AJson.AddArray('List');
  ListItem :=  TStringList.Create;
  ListItem.Delimiter := ',';
  ListItem.DelimitedText := ListStr.Strings[0].Replace('"','',[rfReplaceAll]);
  CurPos := ListItem.IndexOf('MailImage');
  if CurPos > -1 then
    AJson.Add('HttpItem').AsInteger := CurPos;

  CurPos := ListItem.IndexOf('Image');
  if CurPos > -1 then
    AJson.Add('NameItem').AsInteger := CurPos;

  if AJson.Exists('HttpItem') then
  begin
    for i := 1 to ListStr.Count-1 do
    begin
      CurStr :=  ListStr.Strings[i];
      CurStr := CurStr.Replace('"','',[rfReplaceAll]);
      CurPos := Pos('https://',CurStr);
      if CurPos > 0 then
      begin
        OneJson := AJson.ItemByName('List').Add;
        OneJson.Add('SrcData').AsString := CurStr;
        OneJson.Add('Num').AsInteger := i+1;
        //获取链接
        CurStr := CurStr.Substring(CurPos-1,CurStr.Length);
        CurPos := Pos(',',CurStr);
        if CurPos > 0 then
          CurStr := CurStr.Substring(0,CurPos-1);
        //链接以及名字
        OneJson.Add('Url').AsString := CurStr;
        OneJson.Add('Name').AsString := WixToUUId(CurStr)+'.png';
      end;
    end;
  end
  else
  begin
    for i := 1 to ListStr.Count-1 do
    begin
      CurStr :=   ListStr.Strings[0].Replace('"','',[rfReplaceAll]);
      ListItem.DelimitedText := CurStr;
      CurPos := Pos('https://',ListItem.Strings[AJson.IntByName('HttpItem',0)]);
      if CurPos > 0 then
      begin
        OneJson.Add('SrcData').AsString := CurStr;
        OneJson.Add('Num').AsInteger := i+1;
        OneJson.Add('Url').AsString := ListItem.Strings[AJson.IntByName('HttpItem',0)];
        OneJson.Add('Name').AsString := ListItem.Strings[AJson.IntByName('Image',0)];
      end;
    end;
  end;

  DelaySwitch(20);
  if AJson.ItemByName('List').Count = 0 then
  begin
    SetShowMessageBox(2,'no found url form '+bsSkinEdit1.Text);
    FreeAndNil(ListStr);
    FreeAndNil(AJson);
    FreeAndNil(ListItem);
    bsknbtnDown.Enabled := True;
    Exit;
  end;
  
  //删除重复的数据
  CheckDirJson(AJson.ItemByName('List'),AJson.ValueByName('DesDir','')+'/');
  DelaySwitch(20);
  //
  DownLoadJson(AJson.ItemByName('List'),AJson.ValueByName('DesDir','')+'/');
  SetShowMessageBox(2,'Download csv file sucess.');
  //AJson.SaveToFile(ChangeFileExt(ExtractFileName(bsSkinEdit1.Text),'.Json'));
  FreeAndNil(ListItem);
  FreeAndNil(ListStr);
  FreeAndNil(AJson);
  bsknbtnDown.Enabled := True;
end;

procedure TForm1.bsSkinButton1Click(Sender: TObject);
var
  CurFile   :   string;
begin
  CurFile := SetSkinOpenDialog('csv files|*.csv','Select Csv File',FWorkDir+'\');
  if CurFile.Length > 0 then
    bsSkinEdit1.Text := CurFile;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  path    :   string;
begin
  InitAppDir;
  path := GetCurrentDir;
  FWorkDir :=  path;
  InitGlobalSkinData(Self,bsSkinData1);
  InitBsControl(bsSkinData1,Self);        //初始化BS内部控件
  InitControlSkin(Self,'SkinData',bsSkinData1);

  FDownDir := 'C:\Users\Public\Downloads\Csv2Png';

  Caption :=    'CSV2PNG@THINKSIGN';//+TJGetFileVersion(Application.ExeName);
  bsSkinEdit1.Text := '';
  if not FolderExistStr(FDownDir) then
    CreateDir(FDownDir);

//  if not FolderExistStr(FWorkDir+'/DownLoad') then
//    CreateDir(FWorkDir+'/DownLoad');

  ProgressBar1.Visible := False;
  FDownFile :=   TQDownFile.Create(Self,3);

  FCosHard := TCosHard.Create(Self);
  FCosHard.SetSecretIdAndKey('AKIDe6vv2ByDIejY7RgyytiGEvUVZO7jlHE5', 'sUqwqd4GYbNyVltgDzSffZ7YUO6h1Vki');
  FCosHard.SetKeyMode(1, 60);
  FCosHard.SetHostAddr('ts-1303944486.cos.na-ashburn.myqcloud.com');
  FCosObject := TCosObject.Create('CosObj', FCosHard);
  FCosWixPath := '/App/PC_CSV2PNG';
end;





procedure TForm1.FormDestroy(Sender: TObject);
begin
  FreeAndNil(FCosHard);
  FreeAndNil(FCosObject);
  FreeAndNil(FDownFile);
end;

end.
